package com.org.oracle.service.impl;

import com.org.oracle.mongodb.entity.QuestionComment;
import com.org.oracle.service.QuestionCommentService;
import jakarta.annotation.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class QuestionCommentServiceImpl implements QuestionCommentService {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 根据题目id获取当下所有评论
     * @param questionId 题目id
     * @return 所有评论（父子评论）
     */
    @Override
    public List<QuestionComment> getCommentsByQuestionId(String questionId) {
        // 查询所有与 questionId 相关的评论
        Query query = new Query(Criteria.where("questionId").is(questionId));

        // 查询所有与 questionId 相关的评论
        List<QuestionComment> comments = mongoTemplate.find(query, QuestionComment.class);

        // 按 rootId 分组
        Map<String, List<QuestionComment>> groupedByRootId = comments.stream()
                .collect(Collectors.groupingBy(QuestionComment::getRootCommentId));

        // 获取根评论（rootId = "-1" 的评论）
        List<QuestionComment> topLevelComments = groupedByRootId.getOrDefault("-1", Collections.emptyList());
        // 递归设置子评论
        topLevelComments.forEach(comment -> setChildComments(comment, groupedByRootId));
        return topLevelComments;
    }

    /**
     * 设置父评论的子评论
     * @param parent 父评论
     * @param groupedByRootId rootId的分组
     */
    private void setChildComments(QuestionComment parent, Map<String, List<QuestionComment>> groupedByRootId) {
        // 获取当前评论的子评论
        List<QuestionComment> children = groupedByRootId.getOrDefault(parent.getCommentId(), Collections.emptyList());
        parent.setReplies(children);  // 设置子评论

        // 递归处理每个子评论
        children.forEach(child -> setChildComments(child, groupedByRootId));
    }
}